#import "ClientController.h"

@implementation ClientController

-(void)startClient
{	NSString * addr = @"192.168.0.111";
	int port = 8001;
	[NSStream getStreamsToHost:[NSHost hostWithAddress:addr] port:port inputStream:&inStream outputStream:&outStream];
}

-(void)writeString:(NSString *) string 
{
	char * ends="\r\n";
    NSData *messageAsData = [string dataUsingEncoding:NSUTF8StringEncoding];
    [outStream write: (uint8_t * )[messageAsData bytes] maxLength:[messageAsData length]];//(const uint8_t *) [messageAsData bytes] maxLength: [messageAsData length]];
	[outStream write:(uint8_t *)ends maxLength:2];
}


-(void)closeStreams{
	
    [inStream close];
    [outStream close];
    [inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inStream setDelegate:nil];
    [outStream setDelegate:nil];
    [inStream release];
    [outStream release];
    inStream = nil;
    outStream = nil;
}

-(void)openStreams{
    [inStream retain];
    [outStream retain];
    [inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inStream open];
    [outStream open];
}

-(bool) receiveData
{
	uint8_t buffer[32768];
	if([inStream read:buffer maxLength:32768])
	{
		
		NSString * str = [[NSString alloc]initWithUTF8String:(char *)buffer];//:buffer length:32768 encoding:NSUTF8StringEncoding];
		str = [str stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\0"];
//		char * cs = buffer;
		//if([str isEqualToString:@"END"])
		//	return FALSE;*/
		NSLog(@"%@",str);
		[str release];
		return TRUE;
	}
	else 
		return FALSE;
	
}

- (void)dealloc {
    [super dealloc];
}

@end
